CODE 111. Valid Parentheses

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/11/06/2013-11-06-CODE 111 Valid Parentheses/

访问原文「CODE 111. Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are
all valid but "(]" and "([)]" are
not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public boolean isValid(String s) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
char[] ss = s.toCharArray();
Stack<Character> stack = new Stack<Character>();
for (char c : ss) {
if ('(' == c || '{' == c || '[' == c) {
stack.add(c);
} else {
if (stack.isEmpty()) {
return false;
}
if (')' == c && stack.pop() != '(') {
return false;
} else if (']' == c && stack.pop() != '[') {
return false;
} else if ('}' == c && stack.pop() != '{') {
return false;
}
}
}
if (stack.isEmpty()) {
return true;
} else {
return false;
}
}
Jerky Lu wechat
欢迎加入微信公众号